package com.dx.financehy.config.security;

import com.dx.financehy.utils.enums.LoginMode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * <pre>
 * @描述：
 * @作者：CLD
 * @创建时间：2021-12-18 16:31
 * </pre>
 **/
@Component
@Slf4j
public class MyAuthenticationProvider extends DaoAuthenticationProvider {

    private final PasswordEncoder passwordEncoder;

    public MyAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
        super();
        setUserDetailsService(userDetailsService);
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        MyUsernamePasswordAuthenticationToken myAuthentication = (MyUsernamePasswordAuthenticationToken) authentication;
        String presentedPassword = (String) myAuthentication.getCredentials();
        LoginMode loginMode = myAuthentication.getLoginMode();
        if (userDetails == null || myAuthentication.getCredentials() == null) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        if (LoginMode.PW.equals(loginMode) && !passwordEncoder.matches(presentedPassword, userDetails.getPassword())) { // 密码登录
            throw new BadCredentialsException("用户名或密码错误");
        }
        if (LoginMode.OTHER.equals(loginMode) && !userDetails.getPassword().equals(presentedPassword)) { // 其他方式登录
            throw new BadCredentialsException("用户名或密码错误");
        }

    }

}
